package com.ht.interfaces.controller;

import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ht.api.db.bean.AjaxResult;
import com.ht.api.db.bean.DataResult;
import com.ht.api.db.bean.SessionBean;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.request.HandleRequestUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 通用接口
 * @author asq
 * @createTime 2024年12月21日 20:21:44
 */
@RestController
@Slf4j
public class CommonController {

    @GetMapping("/call/{key}")
    public AjaxResult getHost(@PathVariable String key,
							  @RequestHeader("Host") String host,
							  @RequestHeader(value = "openid", required = false) String openid,
							  @RequestParam(required = false) Map<String, String> params) {
    	// url参数转JSONObject
	    JSONObject paramUrl = new JSONObject();
        if (params != null) {
        	paramUrl.putAll(params);
        }
		
		return postHost(key, host, openid, JSONUtil.createObj().set("param", paramUrl));
    }

    @PostMapping("/call/{key}")
    public AjaxResult postHost(@PathVariable String key,
							   @RequestHeader("Host") String host,
							   @RequestHeader(value = "openid", required = false) String openid,
							   @RequestBody JSONObject param) {
    	 // 优先使用原始Host
		log.info("host : " + host);

		host = "m.htiannet.com";

		// 验证请求参数
    	if (StrUtil.isBlankIfStr(param.getStr("param"))) {
			throw new HtException("参数param不能为空~");
		}
    	
		// 调用接口
    	DataResult result = HandleRequestUtil.callFunc(SessionBean.createByHost(host, openid), key, param);
		
    	// 返回给前端
    	if (StrUtil.isBlank(result.getMsg())) {
    		return AjaxResult.success(result.getData());
    	} else {
    		return AjaxResult.success(result.getMsg(), result.getData());
    	}
    }
}
